package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 捐赠详情页面
 */
public class DonationDetailActivity extends BaseActivity {
    private static final String TAG = "RechargeDetailActivity";

    public static void startActivity(Context context, String donationId) {
        context.startActivity(new Intent(context, DonationDetailActivity.class).putExtra("donationId", donationId));
    }

    public static void startActivity(Fragment fragment, String donationId, int requestCode) {
        fragment.startActivityForResult(new Intent(fragment.getContext(), DonationDetailActivity.class).putExtra("donationId", donationId), requestCode);
    }

    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_amount_tips)
    TextView tv_status;
    @BindView(R.id.iv_sender_avatar)
    ImageView iv_senderAvatar;
    @BindView(R.id.tv_sender_name)
    TextView tv_senderName;
    @BindView(R.id.tv_donation_id)
    TextView tv_donationId;
    @BindView(R.id.iv_topic_icon)
    ImageView iv_topicIcon;
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.iv_arrow1)
    ImageView iv_arrow1;
    @BindView(R.id.iv_receiver_avatar)
    ImageView iv_receiverAvatar;
    @BindView(R.id.tv_receiver_name)
    TextView tv_receiverName;
    @BindView(R.id.tv_label)
    TextView tv_label;
    @BindView(R.id.tv_updated)
    TextView tv_updated;
    @BindView(R.id.tv_created)
    TextView tv_created;
    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    private String donationId;
    private Donation donation;
    private User sendUser;  //捐赠的user对象


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_donation_detail);
        ButterKnife.bind(this);
        donationId = getIntent().getStringExtra("donationId");
        loadData();
        tv_customerService.setOnClickListener(v -> contactCustomerService());
    }

    private void loadData() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .queryDonation(donationId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        Object data = body.getData();
                        if (data != null) {
                            JSONObject jsonObject = (JSONObject) data;
                            donation = jsonObject.getObject("donation", Donation.class);
                            if (jsonObject.containsKey("sendUser")) {
                                sendUser = jsonObject.getObject("sendUser", User.class);
                            }
                            setupViews(donation);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void setupViews(Donation donation) {
        Integer type = donation.getType();
        if (type != null) {
            switch (type) {
                case Constant.DONATION_TYPE_TO_PERSON:
                    donationToPerson();
                    break;
                case Constant.DONATION_TYPE_TO_EXPOSURE:
                    donationToExposure();
                    break;
                case Constant.DONATION_TYPE_TO_REWORD:
                    donationToReward();
                    break;
                case Constant.DONATION_TYPE_ADVERTISEMENT:
                    donationPutAdvertisement();
                    break;
                case Constant.DONATION_TYPE_TO_SCHOOL:
                    donationToSchool();
                    break;
                case Constant.DONATION_TYPE_TO_INDUSTRY:
                    donationToIndustry();
                    break;
                case Constant.DONATION_TYPE_TO_AREA:
                    donationToArea();
                    break;

            }
        }
        tv_amount.setText(Utils.moneyFormat(donation.getAmount()));
        tv_donationId.setText(donation.getId());
        tv_created.setText(DateUtils.dateToString(donation.getCreated(), DateUtils.FORMAT_TIMESTAMP));
    }

    /**
     * 投放广告位，生产广告位订单的时候，自动捐赠
     * 这样的捐赠是不能拆回的
     */
    private void donationPutAdvertisement() {
        tv_type.setText("广告位投放自动生成");
        switch (donation.getStatus()) {
            case Constant.DONATION_STATUS_COULD_NOT_REVOKE:
                tv_status.setText("[自动生成捐赠 不可拆回]");
                tv_status.setTextColor(getResources().getColor(R.color.text_black));
                iv_arrow1.setVisibility(View.GONE);
                iv_receiverAvatar.setVisibility(View.GONE);
                tv_receiverName.setVisibility(View.GONE);
                tv_label.setVisibility(View.GONE);
                tv_updated.setVisibility(View.GONE);
                showSenderInfo(UserProfileManager.getInstance().getLoginUserInfo());
                showTopicInfo(donation.getAttachTopic());
                break;
            case Constant.DONATION_STATUS_FORWARD:
                donationToTopicAlreadyForward();
                break;
            default:
                Log.e(TAG, "donationPutAdvertisement: 还有状态未处理...");

        }
    }

    private void donationToArea() {
        tv_type.setText("捐赠到地区");
        switch (donation.getStatus()) {
            case Constant.DONATION_STATUS_COULD_REVOKE:
                donationToTopicCouldRevoke();
                break;
            case Constant.DONATION_STATUS_ACTIVE_REVOKE:
                donationToTopicRevoked();
                break;
            case Constant.DONATION_STATUS_FORWARD:
                donationToTopicAlreadyForward();
                break;
            default:
                Log.e(TAG, "donationToArea: 还有状态未处理...");
        }
    }

    private void donationToIndustry() {
        tv_type.setText("捐赠到行业");
        switch (donation.getStatus()) {
            case Constant.DONATION_STATUS_COULD_REVOKE:
                donationToTopicCouldRevoke();
                break;
            case Constant.DONATION_STATUS_ACTIVE_REVOKE:
                donationToTopicRevoked();
                break;
            case Constant.DONATION_STATUS_FORWARD:
                donationToTopicAlreadyForward();
                break;
            default:
                Log.e(TAG, "donationToIndustry: 还有状态未处理...");
        }
    }

    /**
     * 捐赠到学校
     */
    private void donationToSchool() {
        tv_type.setText("捐赠到学校");
        switch (donation.getStatus()) {
            case Constant.DONATION_STATUS_COULD_REVOKE:
                donationToTopicCouldRevoke();
                break;
            case Constant.DONATION_STATUS_ACTIVE_REVOKE:
                donationToTopicRevoked();
                break;
            case Constant.DONATION_STATUS_FORWARD:
                donationToTopicAlreadyForward();
                break;
            default:
                Log.e(TAG, "donationToSchool: 还有状态未处理...");
        }

    }

    private void donationToReward() {
        tv_type.setText("捐赠到悬赏");
        switch (donation.getStatus()) {
            case Constant.DONATION_STATUS_COULD_REVOKE:
                donationToTopicCouldRevoke();
                break;
            case Constant.DONATION_STATUS_ACTIVE_REVOKE://捐赠主动拆回的情况
                donationToTopicRevoked();
                break;
            case Constant.DONATION_STATUS_COULD_NOT_REVOKE://悬赏已经结算，捐赠转给了 赏金获得者
            case Constant.DONATION_STATUS_FORWARD://悬赏已经结算，捐赠转给了 赏金获得者
                tv_status.setText("[悬赏已结算 捐赠已转发给赏金获得者]");
                tv_status.setTextColor(getResources().getColor(R.color.text_black));
                tv_label.setText("结算时间");
                tv_updated.setText(DateUtils.dateToString(donation.getUpdated(), DateUtils.FORMAT_TIMESTAMP));
                //sendUser == null,说明是捐赠者查看捐赠详情，否则就是受捐者查看捐赠详情，后端返回了捐赠者对象
                showSenderInfo(sendUser == null ? UserProfileManager.getInstance().getLoginUserInfo() : sendUser);
                showTopicInfo(donation.getAttachTopic());
                showReceiverInfo(donation.getTargetUser());
                break;
            case Constant.DONATION_STATUS_PASSIVE_REVOKE://悬赏取消，捐赠被动拆回的情况
                tv_status.setText("[悬赏取消 捐赠自动返还]");
                tv_status.setTextColor(getResources().getColor(R.color.text_gray));
                tv_status.setOnClickListener(null);
                iv_arrow1.setVisibility(View.GONE);
                iv_receiverAvatar.setVisibility(View.GONE);
                tv_receiverName.setVisibility(View.GONE);
                tv_label.setText("拆回时间");
                tv_updated.setText(DateUtils.dateToString(donation.getUpdated(), DateUtils.FORMAT_TIMESTAMP));
                showSenderInfo(UserProfileManager.getInstance().getLoginUserInfo());
                showTopicInfo(donation.getAttachTopic());
                break;
            default:
                Log.e(TAG, "donationToReward: 还有状态未处理...");
        }

    }

    /**
     * 捐赠到主题  且 捐赠已经转发
     */
    private void donationToTopicAlreadyForward() {
        tv_status.setText("[已转赠 点击进入转赠详情]");
        tv_status.setTextColor(getResources().getColor(R.color.text_black));
        tv_status.setOnClickListener(v -> ForwardDetailsActivity.startActivity(DonationDetailActivity.this, donation.getfId()));
        tv_label.setText("转赠时间");
        //对于转赠分拆形成的子捐赠，生成时间也就是转赠时间
        Date forwardUpdate = donation.getUpdated() != null ? donation.getUpdated() : donation.getCreated();
        tv_updated.setText(DateUtils.dateToString(forwardUpdate, DateUtils.FORMAT_TIMESTAMP));
        showSenderInfo(UserProfileManager.getInstance().getLoginUserInfo());
        showTopicInfo(donation.getAttachTopic());
        showReceiverInfo(donation.getTargetUser());
    }

    /**
     * 捐赠到主题 且 已经拆回
     */
    private void donationToTopicRevoked() {
        tv_status.setText("[已拆回]");
        tv_status.setTextColor(getResources().getColor(R.color.text_gray));
        tv_status.setOnClickListener(null);
        iv_arrow1.setVisibility(View.GONE);
        iv_receiverAvatar.setVisibility(View.GONE);
        tv_receiverName.setVisibility(View.GONE);
        tv_label.setText("拆回时间");
        tv_updated.setText(DateUtils.dateToString(donation.getUpdated(), DateUtils.FORMAT_TIMESTAMP));
        showSenderInfo(UserProfileManager.getInstance().getLoginUserInfo());
        showTopicInfo(donation.getAttachTopic());
    }

    /**
     * 捐赠到主题  可拆回
     */
    private void donationToTopicCouldRevoke() {
        tv_status.setText("[可拆回]");
        tv_status.setTextColor(getResources().getColor(R.color.text_black));
        tv_status.setOnClickListener(v -> revokeDonation());
        iv_arrow1.setVisibility(View.GONE);
        iv_receiverAvatar.setVisibility(View.GONE);
        tv_receiverName.setVisibility(View.GONE);
        tv_label.setVisibility(View.GONE);
        tv_updated.setVisibility(View.GONE);
        showSenderInfo(UserProfileManager.getInstance().getLoginUserInfo());
        showTopicInfo(donation.getAttachTopic());
    }


    private void donationToPerson() {
        tv_type.setText("捐赠给个人");
        tv_status.setTextColor(getResources().getColor(R.color.text_black));
        tv_label.setText("捐赠时间");
        iv_arrow1.setVisibility(View.GONE);
        iv_topicIcon.setVisibility(View.GONE);
        tv_topicTitle.setVisibility(View.GONE);
        tv_updated.setText(DateUtils.dateToString(donation.getCreated(), DateUtils.FORMAT_TIMESTAMP));
        //sendUser == null,说明是捐赠者查看捐赠详情，否则就是受捐者查看捐赠详情，后端返回了捐赠者对象
        showSenderInfo(sendUser == null ? UserProfileManager.getInstance().getLoginUserInfo() : sendUser);
        showReceiverInfo(donation.getTargetUser());
        if (sendUser == null) {
            tv_status.setText("[已入账对方账户余额  不可拆回]");
        } else {
            tv_status.setText("[已入账至账户余额]");
        }
    }

    private void donationToExposure() {
        tv_type.setText("捐赠到曝光");
        tv_status.setTextColor(getResources().getColor(R.color.text_black));
        tv_label.setText("捐赠时间");
        iv_arrow1.setVisibility(View.GONE);
        iv_topicIcon.setVisibility(View.GONE);
        tv_topicTitle.setVisibility(View.GONE);
        tv_updated.setText(DateUtils.dateToString(donation.getCreated(), DateUtils.FORMAT_TIMESTAMP));
        //sendUser == null,说明是捐赠者查看捐赠详情，否则就是受捐者查看捐赠详情，后端返回了捐赠者对象
        showSenderInfo(sendUser == null ? UserProfileManager.getInstance().getLoginUserInfo() : sendUser);
        showReceiverInfo(donation.getTargetUser());
        if (sendUser == null) {
            tv_status.setText("[已入账对方账户余额  不可拆回]");
        } else {
            tv_status.setText("[已入账至账户余额]");
        }
    }

    private void showSenderInfo(User sender) {
        if (sender == null) {
            return;
        }
        //Glide.with(DonationDetailActivity.this).load(sender.getAvatar()).into(iv_senderAvatar);
        GlideLoadUtils.glideLoad(this, sender.getAvatar(), iv_senderAvatar);
        tv_senderName.setText(sender.getUsername());
        iv_senderAvatar.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) return;
            UserProfileActivity.startActivity(DonationDetailActivity.this, sender);
        });
    }

    private void showTopicInfo(Topic topic) {
        if (topic == null) {
            return;
        }
        String iconUrl = Utils.getIconUrlScale20(topic);
        if (GlideLoadUtils.isActivityAlive(this)) {
            Glide.with(this).load(iconUrl).transform(new CircleCrop()).into(iv_topicIcon);
        }
        tv_topicTitle.setText(topic.getTitle());
        iv_topicIcon.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) return;
            TopicDetailsActivity.startActivity(DonationDetailActivity.this, topic.getId());
        });
    }

    private void showReceiverInfo(User receiver) {
        if (receiver == null) {
            return;
        }
        //Glide.with(DonationDetailActivity.this).load(receiver.getAvatar()).into(iv_receiverAvatar);
        GlideLoadUtils.glideLoad(this, receiver.getAvatar(), iv_receiverAvatar);
        tv_receiverName.setText(receiver.getUsername());
        iv_receiverAvatar.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) return;
            UserProfileActivity.startActivity(DonationDetailActivity.this, receiver);
        });
    }

    /**
     * 联系客服
     */
    void contactCustomerService() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(DonationDetailActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 拆回、取消捐赠
     *
     * @return
     */
    private void revokeDonation() {


        ConfirmDialog dialog = new ConfirmDialog(this, "提示", "拆回该笔捐赠？", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {

                progressBar.setVisibility(View.VISIBLE);

                Donation updateDonation = new Donation();
                updateDonation.setId(donation.getId());
                updateDonation.setoId(donation.getoId());
                updateDonation.setAmount(donation.getAmount());
                RetrofitManager.getInstance().createRequest(DonationService.class)
                        .revokeDonation(updateDonation)
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                progressBar.setVisibility(View.GONE);
                                CommonResult result = response.body();
                                if (!response.isSuccessful() || result == null) {
                                    Log.e(TAG, "onResponse: " + response.message());
                                    showToast(getString(R.string.system_busy));
                                    return;
                                }

                                if (result.isError()) {
                                    Integer status = result.getStatus();
                                    Log.e(TAG, "onResponse: " + result.getMsg());
                                    switch (status) {
                                        case Constant.NO_AUTHORITY:
                                            showToast("你没有权限拆回该笔捐赠");
                                            break;

                                        case Constant.DONATION_STATUS_ERROR:
                                            //捐赠状态错误，从后端返回最新的捐赠信息，然后刷新页面
                                            Object data = result.getData();
                                            if (data != null) {
                                                Donation donation1 = ((JSONObject) data).toJavaObject(Donation.class);
                                                donation.setStatus(donation1.getStatus());
                                                setupViews(donation);
                                            }
                                            break;
                                        default:
                                            showToast(getString(R.string.system_busy));
                                            break;
                                    }
                                    return;
                                }
                                showToast("拆回捐赠完成");
                                BigDecimal bigDecimal = (BigDecimal) result.getData();
                                double balance = bigDecimal.setScale(2, RoundingMode.DOWN).doubleValue();
                                //更新本地余额
                                UserProfileManager.getInstance().setUserBalance(balance);
                                //广播余额变动
                                LocalBroadcastManager.getInstance(DonationDetailActivity.this).sendBroadcastSync(new Intent(Constant.ACTION_USER_INFO_CHANGE));
                                donation.setStatus(Constant.DONATION_STATUS_ACTIVE_REVOKE);
                                donation.setUpdated(new Date());
                                //当捐赠拆回后，回传更改状态后的捐赠对象给之前的页面
                                setResult(RESULT_OK, new Intent().putExtra("donation", donation));
                                setupViews(donation);
                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                progressBar.setVisibility(View.GONE);
                                Log.e(TAG, "onFailure: " + t.getMessage());

                            }
                        });
            }
        });
        dialog.show();


    }


}